﻿@page "/CatTalk"
@inject HttpClient _HttpClient
@inject IMessageService _Message
@inject NavigationManager _NM
<GridRow Justify="center">
    <GridCol Xs="24" Sm="20" Md="20" Lg="18" Xl="18">
        <div>
            <Title Level="1">猫咪论坛</Title>
            <Title Level="3">猫咪天气站</Title>
            <Paragraph>在进行友善的喵喵交流前，我们需要关注一下今天的天气</Paragraph>
            <Paragraph>
                <AntDesign.Charts.Line @ref="@chart1" Data="chartData" Config="config" />
            </Paragraph>
            <Paragraph>
                上文数据是从DotNet服务器后台进行获取的，也是本网站唯一一个从DotNet服务器的案例。后面的操作（包含数据库的操作），都将在JavaWeb上进行编写代码。
            </Paragraph>
            <Title Level="3">猫咪论坛总站</Title>
            <Title Level="4">论坛消息一览</Title>
            <div style="border-radius:10px;background-color:white;overflow:hidden">
                @if (passageData.Count == 0) {
                    <Empty></Empty>
                } else {
                    <AntList Bordered="true" DataSource="@passageData" ItemLayout="ListItemLayout.Horizontal" Split="true" TItem="Passage" Style="overflow:hidden;">
                        <ListItem>
                            <ChildContent>
                                <ListItemMeta AvatarTemplate="avatar" Description="@context.Body">
                                    <TitleTemplate>
                                        <a href="CatTalk/passages/view/@context.Id">@context.Title</a>
                                    </TitleTemplate>
                                </ListItemMeta>
                                <a href="/CatTalk/Passages/update/@context.Id">编辑</a>
                                <a style="color:red;margin:0 0 0 10px" @onclick="()=>{this.DeletePassage(context.Id);}">删除</a>
                            </ChildContent>
                        </ListItem>
                    </AntList>
                }
            </div>
            分页有个Bug，就是显示不全面，当前页数是：@GobalManager.nowPageIndex
            @if (GobalManager.countPassages > 5) {
                <Pagination PageIndex="@GobalManager.nowPageIndex" PageSize="5" Total="@GobalManager.countPassages" OnChange="pageChange"></Pagination>
            }
            <Title Level="4">我要发贴</Title>
            <Paragraph>
                请在下面的输入框中，输入您想要分享的内容。<br />由于想要偷点懒，所以暂时是不能上传图片之类的东西哦！但是支持Latex数学公式的使用。
            </Paragraph>
            <Input @bind-Value="@newPassage.Title" placeholder="标题" />
            <Vditor.Editor Upload="upload" Mode="wysiwyg" Height="400" MinHeight="200" @bind-Value="@newPassage.Body" @ref="editor"></Vditor.Editor>
            @if (GobalManager.myUsrInfo == null) {
                <Alert Message="未登录网站的猫猫，有些功能将不能使用" Type="@AlertType.Error" />
            }
            <Button Type="primary" OnClick="@PostPassage" Loading="@isLoading">
                发布消息
            </Button>
            <Title Level="2">其他说明</Title>
            <div style="height:300px">
                <Carousel DotPosition="@CarouselDotPosition.Top" Style="height:300px">
                    <Carousel>
                        <CarouselSlick>
                            <!--设置背景-->
                            <div class="mBackMask" style=" background-image: url('https://pic3.zhimg.com/80/v2-c7cd654b5615147dbf9145475c1999a6_720w.webp');" />
                            <!--主要内容-->
                            <div class="mInieSlick">
                                <p style=" color: #fff;">摘抄自《蒲公英的女孩》</p>
                                <h1 style=" color: #fff;">前天，我遇到了小兔子；昨天，我遇到了鹿儿；今天，我遇见了你</h1>
                                <p style=" color: #fff;">Day before yesterday I saw a rabbit, and yesterday a deer, and today you.</p>
                                <a href="https://zhuanlan.zhihu.com/p/452317542" target="_blank">了解更多</a>
                            </div>
                        </CarouselSlick>
                        <CarouselSlick>
                            <!--设置背景-->
                            <div class="mBackMask" style=" background-image: url('https://pic3.zhimg.com/v2-2377dbabce345d5207931d591ffeb400_b.jpg?consumer=ZHI_MENG');" />
                            <!--主要内容-->
                            <div class="mInieSlick">
                                <p style=" color: #fff;">摘抄自《CLANNAD》</p>
                                <h1 style=" color: #fff;">“开心的事情，现在才要开始呢。”</h1>
                                <p style=" color: #fff;">——风子</p>
                                <a href="https://zhuanlan.zhihu.com/p/452317542" target="_blank">了解更多</a>
                            </div>
                        </CarouselSlick>
                    </Carousel>
                </Carousel>
            </div>
            <Title Level="2">项目说明</Title>
            具体请看本项目的ReadMe文件
            <div style="border-radius:10px;background-color:#fbfbfb;box-shadow: inset 0px 0px 5px #0000002e;overflow:hidden">
                <GridRow>
                    <GridCol Xs="24" Sm="8" Xl="8" Style="background-image:url('./Resources/IMG_1267 (2).JPG');background-size:cover;min-height:200px;background-position:center"></GridCol>
                    <GridCol Xs="24" Sm="16" Xl="16">
                        <div style="padding:50px">
                            <Title Level="3">
                                前端项目说明：
                            </Title>
                            <Paragraph>
                                <ul>
                                    <li>
                                        ✨采用C#语言编写的前端，配合少量的JS实现，先进的WASM提供Runtime托管支持，性能翻倍。是PWA，单页面程序！
                                    </li>
                                    <li>
                                        ✨支持记住密码，自动验证！
                                    </li>
                                    <li>
                                        ✨支持SQL数据库增删查改。
                                    </li>
                                </ul>
                            </Paragraph>
                        </div>
                    </GridCol>
                </GridRow>
            </div>
            <br />
            <div style="border-radius:10px;background-color:#fbfbfb;box-shadow: inset 0px 0px 5px #0000002e;overflow:hidden">
                <GridRow>
                    <GridCol Xs="24" Sm="16" Xl="16">
                        <div style="padding:50px">
                            <Title Level="3">
                                后端项目说明：
                            </Title>
                            <Paragraph>
                                <ul>
                                    <li>
                                        ✨由Asp.Net Core混合JavaServlet编写。
                                    </li>
                                    <li>
                                        ✨如果不是因为学校要求，我应该不会把Java混合在里面，不用担心，Java混合的部分只有老师上课讲的内容，Servlet，好吧，是虽然我确实不知道老师上课到底讲了啥。@("o((>ω< ))o")
                                    </li>
                                    <li>
                                        <Text Strong>
                                            ✨数据库连接使用了JDBC，并且用了懒汉单例模式，别担心，代码都有超级详细的注解！
                                        </Text>
                                    </li>
                                </ul>
                            </Paragraph>
                        </div>
                    </GridCol>
                    <GridCol Xs="24" Sm="8" Xl="8" Style="background-image:url('./Resources/PM03.JPG');background-size:cover;min-height:200px;background-position:center"></GridCol>
                </GridRow>
            </div>
        </div>
    </GridCol>
</GridRow>

<Modal Title="@("正在删除一篇文章")"
       Visible="@_visible"
       OnOk="()=>{this.DeletePassageST2();}"
       OnCancel="()=>{_visible=false;}"
       ConfirmLoading="@_confirmLoading"
       MaskStyle="backdrop-filter: blur(3px);"
       OkText="@("确定删除")">
    <p style="color:black">您确定要删除这篇文章嘛？喵。</p>
    <p style="color:black">删除文章后，将不可以恢复这篇文章。</p>
</Modal>

<style>
    p {
        color: black;
    }
    /*CSS 轮播 */
    .ant-carousel {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        font-variant: tabular-nums;
        line-height: 1.5715;
        list-style: none;
        font-feature-settings: 'tnum';
        height: max-content;
        border-radius: 10px;
        overflow: hidden;
    }

        .ant-carousel .slick-slide {
            text-align: center;
            background: #364d79;
            overflow: hidden;
            height: 300px;
        }

    .mInieSlick {
        color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
        top: -300px;
        height: 300px;
    }

        .mInieSlick h1, h2, p {
        }

    .mBackMask {
        height: 300px;
        width: 100%;
        background-size: cover;
        position: relative;
        filter: blur(2px) brightness(0.5);
    }
</style>

@code {
    //MarkdownUpload
    Editor editor;
    Vditor.Models.Toolbar toolbar = new Vditor.Models.Toolbar();
    Vditor.Models.Upload upload = new Vditor.Models.Upload() {
                Url = "api/UpLoad",
                Max = 2 * 1024 * 1024,
                Accept = "image/*,*.doc,*.docx",
                Multiple = true,
            };
    //
    IChartComponent chart1;
    private WeatherForecast[]? forecasts;
    Object[]? chartData;
    protected override async Task OnInitializedAsync() {
        //获取天气数据
        forecasts = await _HttpClient.GetFromJsonAsync<WeatherForecast[]>(@"http://localhost:5011/api/WeatherForecast/Get");
        chartData = new Object[forecasts.Length];
        for (int i = 0; i < forecasts.Length; i++) {
            chartData[i] = new { date = forecasts[i].Date.ToString(), temperature = forecasts[i].TemperatureC };
        }
        await chart1.ChangeData(chartData);
        //获取消息条数
        this.InitPassage();
        StateHasChanged();
        await base.OnInitializedAsync();
    }
    async void InitPassage() {
      using  var resp = await _HttpClient.GetAsync(GobalManager.serverURL + "/GetPassagesNum");
        StreamReader streanReader = new StreamReader(resp.Content.ReadAsStream(), System.Text.Encoding.UTF8);
        GobalManager.countPassages = int.Parse(streanReader.ReadToEnd());
        Console.WriteLine("页面总条数" + GobalManager.countPassages);
        var resp2 = await GobalManager.GetPassages(GobalManager.nowPageIndex);
        if (resp2 != null) {
            passageData.Clear();
            foreach (var item in resp2) {
                if (item != null) {
                    if (item.Body.Length > 50) {
                        item.Body = item.Body.Substring(0, 50);
                        item.Body += "...";
                    }
                    passageData.Add(item);
                }
            }
        }
        StateHasChanged();
    }
    LineConfig? config = new LineConfig() {
                Title = new AntDesign.Charts.Title() {
                    Text = "天气",
                    Visible = true
                },
                Description = new Description() {
                    Visible = true,
                    Text = "近几日的喵星天气数据（随机瞎编写的）"
                },
                ForceFit = true,
                Padding = "auto",
                XField = "date",
                YField = "temperature",
                Point = new LineViewConfigPoint {
                    Visible = true
                },
                YAxis = new ValueAxis {
                    Nice = true
                },
                Label = new Label {
                    Visible = false
                }
            };
    //展示文章列表
    public List<Passage> passageData = new List<Passage> { };
    RenderFragment avatar = @<Avatar Src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202111%2F09%2F20211109163907_cb810.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673973800&t=de92108f1a0889f37d6fc565af26c28b"></Avatar>;
    //上传文章
    bool isLoading = false;
    Passage newPassage = new Passage() { Title = "【无标题】" };
    async void PostPassage() {
        if (GobalManager.myUsrInfo == null) {
            _Message.Error("您尚未登录");
        } else {
            isLoading = true;
            newPassage.UsrId = GobalManager.myUsrInfo.ID;
            try {
                using var resp = await _HttpClient.PostAsJsonAsync<Passage>(GobalManager.serverURL + @"/AddPassage", newPassage);
                isLoading = false;
                _Message.Info("发送成功");
                this.InitPassage();
                StateHasChanged();
            }
            catch (Exception e) {
                await _Message.Error(e.Message);
            }
        }
    }
    //分页显示
    AntList<List<Passage>> antList;
    void pageChange(PaginationEventArgs args) {
        if (args.Page > 0)
            GobalManager.nowPageIndex = args.Page;
        this.InitPassage();
    }
    //删除一篇文章
    bool _confirmLoading = false;
    bool _visible = false;
    int deleteId = 0;
    void DeletePassage(int id) {
        _visible = true;
        deleteId = id;
    }
    async void DeletePassageST2() {
        Console.WriteLine("要删除的文章：" + deleteId);
        try {
            await _HttpClient.GetAsync(GobalManager.serverURL + "/DeletePassage?id=" + deleteId);
            _Message.Info("删除文章成功");
        }
        catch (Exception ex) {
            _Message.Error("删除文章失败");
            _Message.Error(ex.Message.ToString());
        }
        _visible = false;
        StateHasChanged();
        this.InitPassage();
    }
    protected override void OnInitialized() {
        GobalManager.dCatTalkBody += new GobalManager.OnStatementChanged(() => { this.StateHasChanged(); });

        string[] keys = { "emoji",
            "headings",
            "bold",
            "italic",
            "strike",
            "link",
            "|",
            "list",
            "ordered-list",
            "check",
            "outdent",
            "indent",
            "|",
            "quote",
            "line",
            "code",
            "inline-code",
            "insert-before",
            "insert-after",
            "|"};

        this.toolbar.Buttons.AddRange(keys.ToList());

        Vditor.Models.CustomToolButton toolbar = new Vditor.Models.CustomToolButton() {
                ClassName = "right",
                Hotkey = "⌘-⇧-S",
                Icon = "<svg><use xlink:href=\"#vditor-icon-export\"></use></svg>",
                Name = "sponsor",
                Tip = "自定义Toolbar",
                TipPosition = "n"
            };

        this.toolbar.Buttons.Add(toolbar);

        string[] keys2 = {"upload",
            "record",
            "table",
            "|",
            "undo",
            "redo",
            "|",
            "fullscreen"};
        this.toolbar.Buttons.AddRange(keys2.ToList());
        base.OnInitialized();
    }
}